import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Login from '@/pages/Login'
import Index from '@/pages/Index'
// import Layout from '@/pages/Layout'
import store from '../store/index' // 加载vuex的store

Vue.use(Router)

const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/HelloWorld',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      path: '/',
      name: 'Index',
      component: Index
    }
  ]
})

// router.beforeEach((to, from, next) => {})
router.beforeEach((to, from, next) => { // to:即将要进入的目标  from 当前正要离开的路由  next： Function 一定要调用该方法来resolve这个钩子，执行效果依赖next方法的调用参数
  // console.log('开始认证')
  if (!(to.name === 'Login')) {
    console.log('获取登录状态')
    let gg = store.getters
    console.log(gg)
    // 普通获取方式,没有配置namespaced
    let username = store.state.userinfo.userName
    console.log(username)
    // 通过getter获取,没有配置namespaced
    let name = store.getters.getUserName
    console.log(name)
    // 普通获取state方式,配置namespaced
    let isLogin = store.state.logininfo.IsLogin
    console.log(isLogin)
    // 通过getter获取,配置namespaced，获取失败
    // let isLogin2 = store.getters.logininfo/getLogin
    // console.log(isLogin2)
    if (!isLogin) {
      // router.push('/login')
      next('/login')
    }
  }
  next()
})

export default router
